package com.ywh.auth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
public class MeController {
    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @Autowired
    private OAuth2RestTemplate restTemplate;

    @RequestMapping(value = "/me", method = RequestMethod.GET)
    public String me(OAuth2AuthenticationToken authentication) {
        OAuth2AuthorizedClient authorizedClient = this.authorizedClientService.loadAuthorizedClient(
                authentication.getAuthorizedClientRegistrationId(),
                authentication.getName());
        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
        String principalName = authorizedClient.getPrincipalName();

        return accessToken.toString() + "---" + principalName;
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail() {
        return "detail";
    }

    @RequestMapping(value = "/client", method = RequestMethod.GET)
    public String client() {
        String result = restTemplate.postForObject("http://127.0.0.1:8012/me", null, String.class);
        return result;
    }

    @RequestMapping(value = "/api/protected", method = RequestMethod.GET)
    public String protected_resource(@AuthenticationPrincipal Jwt jwt) {
        String tokenId = jwt.getId();
        String subject = jwt.getSubject();
        String value = jwt.getTokenValue();
        Map<String, Object> m = jwt.getClaims();
        return "protected " + subject + " " + tokenId + " " + value + " " + m;
    }

    @RequestMapping("/login/oauth2/code/github")
    public void callback(String code) {
        System.out.println(code);
    }
}
